package com.evil.Listener;

import com.evil.DB_Utils.DB_Utils;
import com.evil.Data.Data;
import com.evil.Log.Log4j_init;
import com.evil.Mail.MailBean;
import com.evil.Mail.SendMail;
import com.evil.QuartzJob.CreateOverItemLogsJob;
import com.evil.Servlet.StartServlet;
import com.evil.Utils.Log;
import com.evil.Utils.PropertiesUtils;
import com.evil.Utils.Utils;
import org.apache.log4j.Logger;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import javax.mail.MessagingException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

/********************************************
 * 工程名：Web
 * 包名：com.evil.Listener
 * 时间：16-9-20 下午4:56
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：Tomcat生命监听
 ********************************************/
public class ContextListener implements ServletContextListener
{
    private static Logger log;
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");

    private SchedulerFactory schedulerFactory;
    private Scheduler scheduler;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent)
    {
        PropertiesUtils utils = new PropertiesUtils();
        DB_Utils.connection(
                utils.get("DB_Name"),
                utils.get("DB_User_Name"),
                utils.get("DB_User_Password"));

        new Log4j_init().initProperty();

        log = Logger.getLogger(ContextListener.class);

        log.info("定时器于" + dateFormat.format(new Date()) + "开启"+"\r\n");

        startJob();
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent)
    {
        DB_Utils.close_connection();
        log.info("定时器于" + dateFormat.format(new Date()) + "销毁"+"\r\n");
        if (!Log.DEBUG)
            sendMail();
        stopJob();
    }

    /**
     * Tomcat关闭时发送邮件
     */
    private void sendMail()
    {
        MailBean bean = new MailBean();
        PropertiesUtils utils = new PropertiesUtils();

        /*bean.setFromAddr("evilbai@sina.com");
        bean.setUserPassword("evil1714698245");
        bean.setToAddr("evilbai@foxmail.com");*/

        String addr = utils.get("sendmail.from.addr");
        String password = utils.get("sendmail.from.password");
        String toAddr = utils.get("sendmail.me");

        bean.setFromAddr(addr);
        bean.setUserPassword(password);
        bean.setToAddr(toAddr);

        bean.setTitle("警告，Tomcat关闭");
        bean.setContent(dateFormat.format(new Date()) + ">>> Tomcat 关闭！"+"\r\n");

        try
        {
            new SendMail().sendFile(bean);
        }
        catch (MessagingException | UnsupportedEncodingException e)
        {
            e.printStackTrace();
            log.info(dateFormat.format(new Date()) + ">>> Tomcat关闭邮件发送失败！"+"\r\n");
        }
    }

    /**
     * 开始定时任务
     */
    private void startJob()
    {
        try
        {
            //首先要通过工厂方法schedulerFactory的一个实现获取一个Scheduler对象作为调度器
            schedulerFactory = new StdSchedulerFactory();
            scheduler = schedulerFactory.getScheduler();

            {
                //每个job都归于一个name和一个group作为任务的坐标，创建一个BaseJob的JobDetail
                JobDetail overItemLogsDetail = JobBuilder
                        .newJob(CreateOverItemLogsJob.class)
                        .withIdentity("job1", "group1")
                        .build();
                CronTrigger overItemLogsTrigger = newTrigger().withIdentity("trigger1", "group1").withSchedule(cronSchedule("0 0 1 * * ?")).build();
                Date overItemLogsDate = scheduler.scheduleJob(overItemLogsDetail, overItemLogsTrigger);

                log.info(overItemLogsDetail.getKey() +
                        " 已被安排执行于: " + dateFormat.format(overItemLogsDate) +
                        "，并且以如下重复规则重复执行: " + overItemLogsTrigger.getCronExpression()+"\r\n");
            }

            scheduler.start();
        }
        catch (SchedulerException e)
        {
            e.printStackTrace();
        }
    }

    private void stopJob()
    {
        try
        {
            scheduler.shutdown();
        }
        catch (SchedulerException e)
        {
            e.printStackTrace();
        }
    }
}














